<?php

namespace app\api\controller\web;

use addons\epay\library\Service;
use app\admin\controller\apply\Confg;
use app\admin\model\deal\Order;
use app\admin\model\memberpoint\Fellow;
use app\admin\model\memberpoint\Integral;
use app\admin\model\nursery\Companyattestation;
use app\admin\model\User;
use app\common\controller\Api;
use app\common\model\Attachment;
use app\common\model\ScoreLog;
use think\Db;
use think\Model;
use think\Validate;

/**
 *  微信
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['userAuth','userTopList','notifyx','rechargeList'];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信支付
     */
    public function weChatPay()
    {
        $amount = $this->request->param('amount');
        $type = $this->request->param('type');
        $f_id = $this->request->param('f_id');
        $ca_id = $this->request->param('ca_id');
        $returnurl = $this->request->param('returnurl', '/mypages/integral');
        $user = $this->auth->getUser();
        $orderid = "wx".time().rand(100000,999999);
        $member_day = 0;
        //1 苗圃认证  2购买会员  3积分充值
        if($type == 1){
            $title = "认证支付";
            $Confg = \app\admin\model\apply\Confg::get(1);
            if($Confg['nursery_certificat'] != $amount){
                $this->error("金额对不上");
            }
            if(!$ca_id) $this->error("认证id不能为空");

        }elseif ($type == 2){
            $title = "购买会员";
            if(!$f_id) $this->error("会员id不能为空");
            $info =  Fellow::get($f_id);
            if($info['price'] != $amount){
                $this->error("金额对不上");
            }

        }else{
            $title = "积分充值";
            if (!$amount || $amount < 0) {
                $this->error("支付金额必须大于0");
            }
            if($user['member_expire_time'] < date('Y-m-d H:i:s')){ // 充值送会员 已经是会员的不送
                $info = Integral::get(1);
                if($info['recharge_rules']){
                    $recharge_rules = json_decode($info['recharge_rules'],true);
                    $fellowList = Fellow::all();
                    $fellowList = array_column($fellowList,null,'id');
                    if($recharge_rules){
                        foreach ($recharge_rules as $v){
                            if($v['enough'] == $amount && isset($fellowList[$v['level']])){
                                $f_id = $v['level'];
                                $member_day = $fellowList[$v['level']]['day'];
                            }
                        }
                    }
                }
            }
        }
        $result  = $this->orderCreate($type,$orderid,$amount,$f_id,$ca_id,$member_day);
        if(!$result)   $this->error('生成订单失败');
        $data = [
            'amount'=> $amount,//支付金额
            'orderid'=>  $orderid,//"订单号",
            'type' =>  "wechat",//wechat 微信  alipay支付宝
            'title'=> $title,
            'notifyurl'=> $this->request->domain() . "/api/web/wechat/notifyx",//"回调地址",
            'returnurl'=> $returnurl,
            'method'=>"miniapp", //支付环境  miniapp(微信小程序)
            'openid'=> $user["openid"],//"用户的OpenID",
        ];

        $result =  \addons\epay\library\Service::submitOrder($data);
        if(isset($result['appId'])){
            $this->success("请求成功", $result);
        }
        $this->error("请求失败", $result);

    }

    /**
     * @throws \think\exception\DbException
     * 充值列表
     */
    public function rechargeList(){
        $info = Integral::get(1);
        $recharge_rules = [];
        if($info['recharge_rules']){
            $list = Fellow::all();
            $list = array_column($list,null,'id');
            $recharge_rules = json_decode($info['recharge_rules'],true);
            foreach ($recharge_rules as &$v){
                $v['level_name'] = '';
                $v['day'] = 0;
                if($v['level'] && isset($list[$v['level']])){
                    $v['level_name'] = $list[$v['level']]['name'];
                    $v['day'] = $list[$v['level']]['day'];
                }
            }

        }
        $this->success("充值列表",$recharge_rules);
    }

    /**
     * @param $type
     * @param $orderid
     * @param $amount
     * @param string $f_id
     * @param string $ca_id
     * @return Order
     * 统一生成订单
     */
    private function orderCreate($type, $orderid, $amount, $f_id = 0, $ca_id = 0, $member_day = 0){
        $user = $this->auth->getUser();
        $data=[
            'user_id' => $user['id'],
            'type'=>$type,
            'state'=>1,
            'order_number'=>$orderid,
            'money'=>$amount,
            'order_time'=>time(),
            'member_day'=>$member_day
        ];
        if($f_id > 0) $data['f_id'] = $f_id;
        if($type == 1) $data['ca_id'] = $ca_id;
        return Order::create($data);
    }

    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype','wechat');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();

        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $result= (new Order())->where(['order_number'=>$out_trade_no])->find();
            if($result){
                switch ($result['type']){
                    case 1:
                       if(!self::nurseryAuth($result)){
                           $this->error('支付失败');
                       }
                       break;
                    case '2':
                        if(!self::userMember($result)){
                            $this->error('支付失败');
                        }
                        break;
                    case '3':
                        if(!self::integral($result,$payamount)){
                            $this->error('支付失败');
                        }
                        break;
                    default:
                        $this->error('支付失败');
                        break;
                }
            }else{
                $this->error('该订单不存在');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('支付失败',$e->getMessage());
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    public static function   nurseryAuth($order){
        Db::startTrans();
        $result = Order::update(['state'=>2,'payment_time'=>time()],['order_number'=>$order['order_number']]);
        if(!$result) {
            Db::rollback();
            return false;
        }
        $result2 = Companyattestation::update(['is_pay'=>1],['id'=>$order['ca_id']]);
        if(!$result2) {
            Db::rollback();
            return false;
        }
        Db::commit();
        return true;
    }

    public static function  userMember($order){
        $time = date('Y-m-d H:i:s');

        if($order['state'] == 1){
            Db::startTrans();
            $FellowInfo = Fellow::get($order['f_id']);
            if(!$FellowInfo || $FellowInfo['day'] <= 0){
                Db::rollback();
                return false;
            }
            $data =[
                'user_id'=>$order['user_id'],
                'order_id'=>$order['id'],
                'f_id'=>$order['f_id'],
                'start_time'=> $time,
                'end_time' => date('Y-m-d H:i:s',strtotime('+'.$FellowInfo['day']. ' day', strtotime($time))),
                'create_time'=>$time,
            ];
            $result2 = Db::name('user_buy_log')->insert($data);

            if(!$result2) {
                Db::rollback();
                return false;
            }
            $result3 = User::update(['level'=>$order['f_id'],'member_expire_time'=>$data['end_time']],['id'=>$order['user_id']]);
            if(!$result3) {
                Db::rollback();
                return false;
            }
            $result = Order::update(['state'=>2,'payment_time'=>time()],['id'=>$order['id']]);
            if(!$result) {
                Db::rollback();
                return false;
            }
            Db::commit();
        }
        return true;
    }

    public static function  integral($order,$payamount){
        $Integral = Integral::get(1);
        if(!$Integral || $Integral['integral'] <= 0) return false;
        if($order['state'] == 1){
            Db::startTrans();
            $result = \app\common\model\User::score($Integral['integral'] * $payamount,$order['user_id'],'积分充值');
            if(!$result) return false;
            if($order['member_day'] > 0){  //充值送会员 已经是会员的不送
                  $user =   \app\common\model\User::get($order['user_id']);
                  if($user){
                      $time = date('Y-m-d H:i:s');
                      $data =[
                          'user_id'=>$order['user_id'],
                          'order_id'=>$order['id'],
                          'f_id'=>$order['f_id'],
                          'start_time'=> $time,
                          'end_time' => date('Y-m-d H:i:s',strtotime('+'.$order['member_day']. ' day', strtotime($time))),
                          'create_time'=>$time,
                      ];
                      $result2 = Db::name('user_buy_log')->insert($data);

                      if(!$result2) {
                          Db::rollback();
                          return false;
                      }
                      $result3 = User::update(['level'=>$order['f_id'],'member_expire_time'=>$data['end_time']],['id'=>$order['user_id']]);
                      if(!$result3) {
                          Db::rollback();
                          return false;
                      }
                  }
            }
            $result = Order::update(['state'=>2,'payment_time'=>time()],['order_number'=>$order['order_number']]);
            if(!$result) {
                Db::rollback();
                return false;
            }
            Db::commit();
        }
        return true;
    }

}
